package com.czxy.enterprise.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.czxy.domain.TbEnPhoto;
import com.czxy.domain.TbPhoto;
import com.czxy.enterprise.service.EnPhotoService;
import com.czxy.enterprise.service.PhotoService;
import com.czxy.enterprise.utils.OssUtils;
import com.czxy.findjob.vo.BaseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * <p>
 * 图片公共表 前端控制器
 * </p>
 *
 * @author xuewen
 * @since 2022-02-02
 */
@RestController
@RequestMapping("/photo")
public class PhotoController {

    @Autowired
    private PhotoService photoService;

    @Autowired
    private OssUtils ossUtils;

    @Autowired
    private EnPhotoService enPhotoService;

    @GetMapping("findById/{id}")
    public BaseResult<TbPhoto> findById(@PathVariable("id") String id){
        TbPhoto photo = photoService.getById(id);
        return BaseResult.ok("查询成功!",photo);
    }
    @PostMapping("/save")
    public BaseResult<TbPhoto> save(@RequestBody TbPhoto tbPhoto){
        photoService.save(tbPhoto);
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("photo_url",tbPhoto.getPhotoUrl());
        List<TbPhoto> list = photoService.list(queryWrapper);
        if (list==null){
            return BaseResult.ok("报错失败");
        }
        return BaseResult.ok("保存成功!",list.get(0));
    }
    @PostMapping("/upload/{enId}")
    public BaseResult upload(@RequestParam("file") MultipartFile file,@PathVariable("enId") Integer id){
        String url = ossUtils.upload(file);
        TbPhoto tbPhoto = new TbPhoto();
        tbPhoto.setPhotoUrl(url);
        boolean save = photoService.save(tbPhoto);
        if (save){
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("photo_url",url);
            List<TbPhoto> list = photoService.list(queryWrapper);
            TbEnPhoto tbEnPhoto = new TbEnPhoto();
            tbEnPhoto.setPhotoId(list.get(0).getId());
            tbEnPhoto.setEnterpriseId(id);
            enPhotoService.save(tbEnPhoto);
        }
        return BaseResult.ok("上传成功");
    }
}

